package demo;

import java.util.Objects;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: ws
 * Date: 2022-11-17
 * Time: 10:57
 */

//要想达到深拷贝，组合类也要有Cloneable接口
class Money implements Cloneable{
    public int money = 10;

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}
class Student implements Cloneable{
    public String name;
    public Money m = new Money();

    public Student(String name) {
        this.name = name;
    }
//浅拷贝
//    @Override
//    protected Object clone() throws CloneNotSupportedException {
//        return super.clone();
//    }
    //深拷贝，要将当前当前拷贝的对象同样克隆一份

    @Override
    protected Object clone() throws CloneNotSupportedException {
        Student student = (Student) super.clone();
        student.m = (Money) this.m.clone();
        return student;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Student student = (Student) o;
        return Objects.equals(name, student.name);
    }
//重写哈希码，根据自定义的类型来确定是否相同（自己定义的成员变量比较）
    @Override
    public int hashCode() {
        return Objects.hash(this.m.money);
//        return Objects.hash(name);
    }
}

public class Test {
    public static void main(String[] args) throws CloneNotSupportedException {
        Student student = new Student("abc");
        Student student1 = (Student) student.clone();
        student1.m.money = 11;
//        System.out.println(student.m.money);
//        System.out.println(student1.m.money);
//        student.m.money = 11;
//        student.name = "cba";
//        System.out.println(student.m.money);
//        System.out.println(student.name);
//        System.out.println(student1.m.money);
//        System.out.println(student1.name);
        Student student3 = student;

//        System.out.println(student3.m.money);
        //比较两个对象地址是否相同呢
        boolean fla0 = student.equals(student3);
//        System.out.println(fla0);
        System.out.println(student.hashCode());
        System.out.println(student1.hashCode());


        //调用的是String的equals方法
//        boolean fla = student.name.equals(student1.name);
//        System.out.println(fla);
    }


}
